<template>
  <a-layout class="layout">

    <a-layout-header  class="searchHeader" style="background-color: white; box-shadow: -10px 10px 10px -10px rgba(0, 0, 0, 0.3); height: 60px" >
      <SearchHeader  :title='pageTitle'/>
    </a-layout-header>

    <a-layout-content :style="{ background: '#f2f2f2',  minHeight: '680px' }">

      <div :bordered="false" :style="{backgroundColor: '#f2f2f2',height: '100%'}">
        <!--<SearchHeader/>-->
        <div  :style="{backgroundColor: 'white',padding: '10px',minWidth: '900px',height: '150px'}">
          <!-- 查询区域 -->
          <div class="table-page-search-wrapper" style="margin-top: 20px">
            <!--<p></p>-->
            <a-form layout="inline">
              <a-row>
                <a-col :span="24" style="text-align: center;margin-left: 50px;">
                  <div style="display:inline-block">
                    <div style="float: left">
                      <a-input style="width: 800px;" size="large" placeholder="标题、关键字、全文" v-model="content"
                               @pressEnter="pressEnterFun">

                        <a-icon slot="suffix" @click="searchDocFun" type="search" style="color:#1890FF;fontSize:22px"/>
                      </a-input>
                      <div class="checkbox" style="width: 750px;text-align: center;margin-top: 10px;margin-left: 20px;">
                        <a-checkbox-group :options="options" v-model="checkboxVuale" @change="onChange" style=" color:black;"/>
                      </div>
                    </div>
                    <div style="float: left;width: 100px;text-align: left;margin-top: -2px">
                  <span style="color: black;margin-left: 20px"  v-show="false">
                   <span>全文检索</span>
                      <a-checkbox  class="checkbox" v-model="boolCheckChange" style="margin-left: 8px" @change="onCheckChange" />
                  </span>
                    </div>
                  </div>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <!-- 查询区域-END -->
        </div>

        <!-- 表格区域 -->
        <div style="background-color:#f2f2f2" class="km-page">
          <div  class="kmb-context-view"></div>
          <a-form layout="inline">
            <a-row>
            <div class="position-bottom-left">
              <!--<a-col :xl="4" :lg="9" :md="10" :sm="24" :offset="1" style="background-color: #f2f2f2;padding: 15px;min-width: 300px">-->
              <div  style="background-color: #f2f2f2;margin-bottom: 20px;">
                <div style="background-color: white;padding: 0; box-shadow:1px 2px 3px 2px #ccc">
                  <a-form layout="inline" style="min-height: 10px">
                    <a-row>
                      <a-col style="background-color: #081C42">
                        <h3 style="color: white;margin-left: 20px;padding:5px">
                          <b>搜索热词</b>
                        </h3>
                      </a-col>
                      <template>
                        <!--<div class="rank">-->
                          <!--<ul class="list" :style="{height:height?`${height}px`:'auto',overflow:'auto'}">-->
                            <!--<li :key="index" v-for="(item, index) in rankListKeyword">-->
                              <!--<span :class="ranking(index)">{{ index + 1 }}</span>-->
                              <!--<span @click="RankingName(item.name)" :class="getClasses(index)" class="hover-effect">{{ item.name }}</span>-->
                              <!--<span>{{ item.total }}</span>-->
                            <!--</li>-->
                          <!--</ul>-->
                          <template>
                            <div ref="wordCloud" style="width: 100%; height: 360px;"></div>
                          </template>
                      </template>
                    </a-row>
                  </a-form>
                </div>
              </div>

              <!--<a-col :xl="4" :lg="9" :md="10" :sm="24" :offset="1" style="background-color: #f2f2f2;padding: 15px;min-width: 300px">-->
              <div  style="background-color: #f2f2f2;margin-bottom: 20px;">
                <div style="background-color: white;padding: 0; box-shadow:1px 2px 3px 2px #ccc">
                  <a-form layout="inline" style="min-height: 10px">
                    <a-row>
                      <a-col style="background-color: #081C42">
                        <h3 style="color: white;margin-left: 20px;padding:5px">
                          <b>业务</b>
                        </h3>
                      </a-col>
                        <h4 v-for="(item,index) in defaultBusinessTypeList" :key="index" class="context-list-item" style="text-align: center;">
                          <span @click="searchBusinessType(item.value)"><el-link :underline="false" >{{item.text}}</el-link></span>
                        </h4>
                    </a-row>
                  </a-form>
                </div>
              </div>
            </div>

           <div class="km-context-right">
              <div style="background-color: #f2f2f2;border-radius: 10px;">
                <div style="padding: 0; box-shadow:1px 2px 3px 2px #ccc">
                  <a-form :pagination="ipagination" layout="inline" style="min-height: 10px">
                    <a-row style="background: white">
                      <a-col style="background-color: #081C42">
                        <h3 style="color: white;margin-left: 10px;padding:5px">
                          <a-icon theme="twoTone"  twoToneColor="#ff2e1b" type="fire"  :style="{ fontSize: '17px', minWidth: '20px',color: '#ff2e1b' }" />
                          <b>推荐</b>
                          <el-select style="float: right;bottom: 1.5px; padding-right: 10px;width: 120px;" v-model="queryParams.sort"  @change="searchFunsort"   size="mini" >
                            <el-option  v-for="item in option" :key="item.label"  :label="item.label" :value="item.value">
                            </el-option>
                          </el-select>
                        </h3>
                      </a-col>
                      <a-col :xl="24" :lg="24" :md="24" :sm="24" style="height: 730px">
                        <div style="width: 98%; margin: 0 auto;" v-for="item in this.dataSource" :key="index">
                          <h3>
                            <b style="cursor: pointer;" @click="previewKmDoc(item)">{{ item.title }}</b>
                            <span style="float: right">
                     <a-icon v-if="item.downloadFlag==1" type="download" title="下载" @click="downloadKmDoc(item)"
                             :style="{ fontSize: '16px', color: '#1890FF'}"/>
                     <a-icon v-else type="download" title="禁止下载"
                             :style="{ fontSize: '16px', color: '#909399'}"/>
                     <a-divider type="vertical"/>
                     <a-icon v-if="item.favourite==0" type="star" title="收藏" @click="addFavouriteKmDoc(item)"
                             :style="{ fontSize: '18px', color: '#1890FF', }"/>
                     <a-icon v-else type="star" theme="filled" title="取消收藏" @click="delFavouriteKmDoc(item)"
                             :style="{ fontSize: '18px', color: '#1890FF', }"/>
                     <a-divider type="vertical"/>
                     <a-icon style="cursor: pointer;" type="eye"  :title="'预览数：'+item.views" @click="previewKmDoc(item)"
                             :style="{ fontSize: '18px', color: '#1890FF', }"/>
                  </span>
                          </h3>
                          <div>
                            {{ item.createBy }} 发布于 {{ item.createTime }}
                          </div>
                          <div style="width: 100%">
                            <hr>
                          </div>
                        </div>

                      </a-col>
                      <div class="pagination-container">
                        <el-pagination
                          v-show="this.total>0"
                          :total="this.total"
                          :current-page="queryParams.pageNo"
                          :page="queryParams.pageNo"
                          :limit="queryParams.pageSize"
                          @current-change="searchFuns"
                        />
                      </div>
                    </a-row>
                  </a-form>
                </div>
              </div>
           </div>
            </a-row>
          </a-form>

          <b-j-modal :title="title"
                     :width="width"
                     :visible="visible"
                     @cancel="handleCancel"
                     cancelText="关闭"
                     :okButtonProps="{ class:{'jee-hidden': true} }">
            <div>
              <div>
                <p-d-f-modal iframe-i-d="pdfIDde" :p-d-furl="PDFurl" :iframeWidth="width"/>
              </div>
            </div>
          </b-j-modal>

        </div>
      </div>
    </a-layout-content>
    <a-layout-footer style="padding: 0">
      <global-footer/>
    </a-layout-footer>
    <!---小讯机器人--->
    <div style="width: 45%;right: 7%; top: 6%;z-index: 10;position: fixed">
      <chatgpt v-show="chatBox==true" :chatId="chatId" @child-event="update"></chatgpt>
    </div>
    <div style="right: 3%; bottom: 4%; position: fixed;z-index: 10;">
      <el-image
        style="width: 50px;height: 50px;cursor: pointer;box-shadow: 0px 0px 5px black;"
        :src="'https://s1.smartalert.online/2023-04-14/1823eda9-5de4-4502-bcfd-81e6f1a234c2.png'"
        v-if="chatBox==false"
        @click="openDialog()"
      ></el-image>
      <el-button style="width:50px;height: 50px;"
                 icon="el-icon-close"
                 type="primary"
                 v-if="chatBox==true"
                 @click="close()"> </el-button>
    </div>
  </a-layout>
</template>

<script>
  import {ajaxGetDictItems, getDictItemsFromCache} from '@/api/api'
  import {ACCESS_TOKEN} from "@/store/mutation-types"
  import {httpPostAction, getAction,httpAction, downloadFileName, getActionPDF} from "../../../api/manage";
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import Vue from "vue";
  import IframePageContent from "../../../components/layouts/IframeFReportView";
  import GlobalFooter from '@/components/page/GlobalFooter';
  import ARow from "ant-design-vue/es/grid/Row";
  import SearchHeader from '../Common/SearchHeader';
  import Chatgpt from "../Common/Chatgpt";
  import RankList from '@/components/chart/RankList';
  import * as echarts from 'echarts';
  import 'echarts-wordcloud';

  export default {
    name: "defaultDocSearch",
    props: {
      title: {
        type: String,
        default: ''
      },
      list: {
        type: Array,
        default: null
      },
      height: {
        type: Number,
        default: null
      }
    },
    mixins: [JeecgListMixin],
    components: {ARow, IframePageContent,GlobalFooter,SearchHeader,Chatgpt,RankList},
    data() {
      return {
        option: [{
          value: '1',
          label: '发布时间'
        }, {
          value: '2',
          label: '更新时间'
        },
          {
          value: '3',
          label: '浏览热度'
          },
        ],
        chatBox: false,
        chatId: '1',
        boolCheckChange:true,
        checkedArray:[],
        topicCodesTree: {
          checked: [],
          halfChecked: [],
        },
        // 查询参数
        queryParams: {
          pageNo: 1,
          sort: '1',
          pageSize: 10
        },
        boolSelect:false,
        treeData:[],
        rankListKeyword:[],
        knowledgeTitle:"知识专题",
        confirmLoading: false,
        PDFurl: '',
        visible: false,
        pdfLoading: false,
        pdfShow: true,
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        title: "预览",
        width: '900',
        defaultBusinessTypeList: [],
        hotTopicReportList: [],
        docDataSource: [],
        loadedRatio: 0,

        topMenuStyle: {
          headerIndexLeft: {},
          topNavHeader: {},
          headerIndexRight: {},
          topSmenuStyle: {}
        },
        pageTitle: "",
        //表头
        columns: [],
        //列设置
        settingColumns: [],
        //要filter的字段
        filterDictCode: 'km_dict_source',
        //  过滤字段数据
        filterOptions: [],
        //列定义
        defColumns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 40,
            align: "center",
            scopedSlots: {customRender: 'indexNum'},
          },
          {
            title: '标题',
            align: "left",
            dataIndex: 'title',
            scopedSlots: {customRender: 'docTitle'},
          },
          {
            title: '文档来源',
            align: "center",
            dataIndex: 'source_dictText',
            width: 150,
            filters: [],
            // scopedSlots: {
            //   filterDropdown: 'filterSource',
            //   filterIcon: 'filterIcon'
            // },
          },
          {
            title: '发文时间',
            align: "center",
            sorter: true,
            dataIndex: 'pubTimeTxt',
            width: 95,
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            width: 70,
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'action'
            }
          },


        ],
        //  分类数据
        options: [],
        // 输入框输入的内容
        content: '',
        // 多选组件使用的变量
        checkboxVuale: [],
        checkedValues: '',
        dataSource: [],
        total: 0,

        itemList: [],
        // 要加载多选的字典
        dictCode: 'km_dict_category',
        // 请求的url地址
        url: {
          rootList: "/sys/category/loadTreeRoot",
          recentlyList: '/KM/kmDocVisitRecord/recentlyVisitDocs',
          defaultBusinessTypeList: '/KM/HomePage/listBusinessType',
          hotTopicReport: '/KM/HomePage/listRecommendTopic',
          list: '/KM/kmDoc/listRecently',
          previewKmDoc: '/KM/kmDoc/previewKmDoc',
          downloadKmDoc: "/KM/kmDoc/downloadKmDoc",
          addFavouriteKmDoc: '/KM/kmDocFavourite/add',
          delFavouriteKmDoc: '/KM/kmDocFavourite/delete',
          listHotKey: "/KM/kmSearchRecord/hotKeywordReport",
        }
      }
    },

    mounted() {
      //当窗口大小变化时，会调用 resizeListener 函数。
      this.initWordCloud();
      this.resizeListener = () => {
        this.initWordCloud();
      };
      window.addEventListener('resize', this.resizeListener);
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.resizeListener);
    },

    created() {
      this.getHotKeyList();
      this.loadTree();
      //设置全局token
      Vue.prototype.token = Vue.ls.get(ACCESS_TOKEN);
      window._CONFIG['token'] = Vue.prototype.token;
      this.hotTopicReportFun();
      this.loadDefaultBusinessTypeFunc();
      this.initDict();
      this.initFilterDict();
      // 调用初始化自定义table列表函数
      this.initColumns();
      this.changeTitle("普通检索");
      this.searchFun()

    },
    methods: {
      openDialog() {
        var timestamp = Date.now();
        this.chatId=timestamp
        this.chatBox = true;
      },
      close() {
        this.chatBox = false;
      },
      update() {
        this.chatBox = false;
      },
      searchFunsort() {
        console.log("=====searchFunsort========")
        this.queryParams.pageNo = 1;
        this.searchFun();
      },

      searchFuns(newPage) {
        this.queryParams.pageNo = newPage;
        this.searchFun();
      },

      searchFun() {
        console.log("=====queryParams========" + JSON.stringify(this.queryParams))
        getAction(this.url.list,this.queryParams).then((res) => {
          this.dataSource=[];
          if (res.success) {
            this.dataSource = res.result.records;
            this.total = res.result.total;
            // console.log("=====首页========" + JSON.stringify(res.result))
            // console.log("=====参数========" + JSON.stringify(this.queryParams))
            // console.log("=====首页列表========" + JSON.stringify(this.dataSource))
          }
        })
      },
      // 加载filter字段选项
      initFilterDict() {
        this.filterOptions = [];

        //优先从缓存中读取字典配置
        // if (getDictItemsFromCache(this.dictCode)) {
        let options = getDictItemsFromCache(this.filterDictCode)
        if(options){
          options.forEach((item, index) => {
            let filterOption = {};
            filterOption.text = item.title;
            filterOption.value = item.value;
            this.filterOptions.push(filterOption);
          });
          console.log(this.filterOptions);
          this.defColumns[2].filters =this.filterOptions;
          return
        }

        //根据字典Code, 初始化字典数组
        ajaxGetDictItems(this.filterDictCode, null).then((res) => {
          if (res.success) {
            let options = res.result
            console.log(options);
            options.forEach((item, index) => {
              let filterOption = {};
              filterOption.text = item.title;
              filterOption.value = item.value;
              this.filterOptions.push(filterOption);
            });
            this.defColumns[2].filters =this.filterOptions;
          }
        })

      },
      // 是否全文检索
      onCheckChange(e){
        this.boolCheckChange=e.target.checked
        console.log(`checked = ${e.target.checked}`);
      },

      // 查找一个节点的所有父节点
      familyTree(treeData, id) {
        var arrTree = [];
        var forFn = function (arr, key) {
          for (var i = 0; i < arr.length; i++) {
            var item = arr[i]
            if (item.key === key) {
              if (item.parentId === "0") {
                break;
              } else {
                console.log("父节点", item.parentId);
                arrTree.push(item.parentId);
                forFn(treeData, item.parentId);
              }
              break
            } else {
              if (item.children != null) {
                forFn(item.children, key);
              }
            }
          }
        }
        forFn(treeData, id);
        return arrTree
      },

      // 树节点选择触发
      onCheck(checkedKeys, checkedNodes) {
        if(checkedKeys.checked.length>1){
          let checkKeys=checkedKeys.checked[1];
          checkedKeys.checked=[];
          checkedKeys.checked.push(checkKeys);
          let checkNodesTitle= checkedNodes.checkedNodes[1];
          checkedNodes.checkedNodes=[];
          checkedNodes.checkedNodes.push(checkNodesTitle);
        }
        console.log("checkedKeys",checkedKeys);
        console.log("checkedNodes",checkedNodes);
        let temp = new Array();
        let tempArray = new Array();
        this.checkedArray = checkedKeys.checked;

        for (let i = 0; i < this.checkedArray.length; i++) {
          let arrTemp = this.familyTree(this.treeData, this.checkedArray[i]);
          temp = temp.concat(arrTemp);
        }
        // 数组去重
        tempArray = [...new Set(temp)];
        console.log("tempArray", tempArray);
        checkedKeys.halfChecked = tempArray;
        let checkedTitle = checkedNodes.checkedNodes;
        this.knowledgeTitle = "";
        for (let i = 0; i < checkedTitle.length; i++) {
          if (this.knowledgeTitle === "") {
            this.knowledgeTitle = checkedTitle[i].data.props.title;
          } else {
            if (checkedTitle[i].data.props.title != null) {
              this.knowledgeTitle = this.knowledgeTitle + "," + checkedTitle[i].data.props.title;
            }
          }
        }
        if(this.knowledgeTitle ===""){
          this.knowledgeTitle="知识专题"
        }
        let topicCodes=checkedTitle[0].data.props.code;
        this.knowledgeTitleFun(topicCodes,this.topicCodesTree,this.knowledgeTitle);
      },

      // 加载树节点，获取树数据
      loadTree() {
        let params = {
          async: false,
          pcode: ""
        };
        getAction(this.url.rootList, params).then(res => {
          if (res.success) {
            if (res.result && res.result.length > 0) {
              this.treeData = res.result
            } else {
              this.treeData = []
            }
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
        })
      },

      // 更改页面标题
      changeTitle(title) {
        let projectTitle = "Smart Aviator"
        // 特殊处理
        document.title = title + ' · ' + projectTitle

      },

      // 自定义列表  列设置更改事件
      onColSettingsChange(checkedValues) {
        var key = this.$route.name + ":colsettings";
        console.log("colsettings", key);
        Vue.ls.set(key, checkedValues, 30 * 7 * 24 * 60 * 60 * 1000)
        this.settingColumns = checkedValues;
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true
          }
          if (this.settingColumns.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns = cols;
      },
      // 自定义列表  初始化
      initColumns() {
        //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

        var key = this.$route.name + ":colsettings";
        console.log("colsettings", key);
        let colSettings = Vue.ls.get(key);
        if (colSettings == null || colSettings == undefined) {
          let allSettingColumns = [];
          this.defColumns.forEach(function (item, i, array) {
            allSettingColumns.push(item.dataIndex);
          })
          this.settingColumns = allSettingColumns;
          this.columns = this.defColumns;
        } else {
          this.settingColumns = colSettings;
          const cols = this.defColumns.filter(item => {
            if (item.key == 'rowIndex' || item.dataIndex == 'action') {
              return true;
            }
            if (colSettings.includes(item.dataIndex)) {
              return true;
            }
            return false;
          })
          this.columns = cols;
        }
      },

      // 加载 分类数据
      initDict() {
        this.options = [];

        //优先从缓存中读取字典配置
        if (getDictItemsFromCache(this.dictCode)) {
          let options = getDictItemsFromCache(this.dictCode)
          options.forEach((item, index) => {
            let person = {};
            person.label = item.title;
            person.value = item.value;
            this.options.push(person);
          });
          return
        }

        //根据字典Code, 初始化字典数组
        ajaxGetDictItems(this.dictCode, null).then((res) => {
          if (res.success) {
            let options = res.result
            options.forEach((item, index) => {
              let person = {};
              person.label = item.title;
              person.value = item.value;
              this.options.push(person);
            });
          }
        })

      },

      // 多选框选择触发
      onChange(checkedValues) {
        this.checkedValues = checkedValues.toString();
        this.checkboxVuale = checkedValues;
        console.log('checked = ', checkedValues);
      },
      // 按回车键触发方法
      pressEnterFun(e) {
        this.$nextTick(() => {
          this.searchDocFun();
        })
      },

      RankingName(name) {
        this.content=name
        console.info("------- this.content-------" + JSON.stringify(this.content))
          this.searchDocFun();
      },

      //专题检索
      knowledgeTitleFun(topicCodes,topicCodesTree,knowledgeTitle){
        let params={};
        params["topicCodes"]=topicCodes;
        params["topicCodesTree"]=topicCodesTree;
        params["knowledgeTitle"]=knowledgeTitle;
        // this.$router.push({name: 'RecommendTopicList',params:params});
        this.$router.push({name: 'docSearch',params:params});
      },

      // 检索
      searchDocFun() {
        let params = {};
        if (this.content !== "" && this.content != null) {
          params['content'] = this.content;
        }
        if (this.checkedValues !== "" && this.checkedValues != null) {
          params['category'] = this.checkedValues;
        }
        // 判断参数是否为空
        if (this.empty(params)) {
          params['column']="_score";
          params['order']="desc";
          params['boolCheckChange']=this.boolCheckChange;
          if (params['content'] != null) {
            params['content'] = params['content'].replace(/，/g, ',');
          }
          this.$router.push({name: 'docSearch', params: params});
        } else {
          this.$message.info("请输入搜索条件");
        }
      },


      loadDefaultBusinessTypeFunc(){
        getAction(this.url.defaultBusinessTypeList).then(res => {
          if (res.success) {
            this.defaultBusinessTypeList = res.result;
          } else {
            this.$message.error("业务加载失败");
          }
        })
      },
      // 热门专题
      hotTopicReportFun() {
        getAction(this.url.hotTopicReport).then(res => {
          if (res.success) {
            this.hotTopicReportList = res.result;
          } else {
            //this.$message.error("热门专题加载失败");
          }
        })
      },

      getHotKeyList(){
        let httpurl = '';
        let method = '';
        httpurl += this.url.listHotKey;
        method = 'get';
        httpAction(httpurl,null, method).then((res) => {
          console.info("-------排行榜日志-------" + JSON.stringify(res))
          if (res.success) {
            Object.keys(res.result).forEach(key=>{
              this.rankListKeyword.push({
                name: res.result[key]
              })
            })
            this.initWordCloud();
          }
        }).finally(() => {
        })
      },

      initWordCloud() {
        // 使用 this.$refs 来访问模板中的 DOM 元素
        if (this.$refs.wordCloud) {
          const myChart = echarts.init(this.$refs.wordCloud);
          // console.info("-------总词数-------" + JSON.stringify(this.rankListKeyword.length))
          const totalItems = this.rankListKeyword.length; // 总词数
          const minWeight = 20; // 设置最小权重值
          const maxWeight = 30; // 设置最大权重值
          const weightRange = maxWeight - minWeight;// 权重范围
          const option = {
            series: [{
              type: 'wordCloud',
              shape: 'star',
              sizeRange: [20, 35],
              rotationRange: [0, 0],
              padding: [8, 8, 8, 8],
              // padding: 0, // 可以根据需要调整内边距
              gridSize: 12,
              drawOutOfBound: true,
              // data: this.rankListKeyword.map(item => ({
              //   name: item.name,
              //   value: Math.floor(Math.random() * (40 - 20 + 1)) + 20  // 随机分配一个20到40的值
              // })),
              data: this.rankListKeyword.map((item, index) => {
                // 计算每个词的权重，第一个词权重最大，最后一个词权重最小
                const weight = Math.round(maxWeight - (weightRange / (totalItems - 1)) * index);
                return {
                  name: item.name,
                  value: weight
                };
              }),
              textStyle: {
                fontFamily: 'sans-serif',
                valueDec: 'px',
                color: function () {
                  return 'rgb(' + [
                    Math.round(Math.random() * 200),
                    Math.round(Math.random() * 200),
                    Math.round(Math.random() * 200)
                  ].join(',') + ')';
                }
              },
              emphasis: {
                textStyle: {
                  color: 'red' // 鼠标悬停时的文字颜色
                }
              }
            }],

          };
          // console.info("-------data-------" + JSON.stringify(option.series))
          myChart.setOption(option);
          // 绑定点击事件
          myChart.on('click', (params) => {
            if (params.componentType === 'series') {
              // 点击的是词云系列
              console.log('Clicked word:', params.name);
              // 这里可以执行你想要的操作，比如跳转到一个新页面或者显示更多信息
              this.RankingName(params.name);
            }
          });
          // 监听窗口大小变化事件
          window.addEventListener('resize', () => {
            if (myChart != null && myChart.dispose != null) {
              myChart.resize();
            }
          });
        } else {
          console.error('Word cloud container not found');
        }
      },

      //  判断对象是否为空
      empty(obj) {
        for (let key in obj) {
          return true;
        }
        return false;
      },

      //批量下载
      downloadKmDocBatch() {
        console.log("批量下载")
        if (!this.url.downloadKmDoc) {
          this.$message.error("请设置url.downloadKmDoc属性!")
          return
        }
        if (this.selectionRows.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return;
        } else {
          var that = this;
          this.$confirm({
            title: "确认下载",
            content: "是否下载选中数据?",
            onOk: function () {
              for (var i = 0; i < that.selectionRows.length; i++) {
                let fileName = i;
                downloadFileName(that.url.downloadKmDoc, {docId: that.selectionRows[i].id})
              }
              // that.loadData();
              that.onClearSelected();
            }
          });
        }
      },

      //访问业务类型
      searchBusinessType(value){
        let params = {};
        params['businessTypes'] = value;
        this.$router.push({name: 'docSearch', params: params});
      },

      // 显示预览窗口，初始化
      previewKmDoc(record) {
        // this.PDFurl = window._CONFIG['domianURL'] + this.url.previewKmDoc + "?docId=" + record.id;
        if(record.previewfileType!=undefined &&record.previewfileType=="default"){
          this.$router.push({
            path: '/Knowledge?id=' + record.id,
          });
        }else {
          this.PDFurl =  this.url.previewKmDoc + "?docId=" + record.id;
          this.title ='预览 - ' + record.title;
          this.visible = true;
          this.pdfLoading = true;
          this.pdfShow = true;
        }
      },
      //关闭预览窗口
      handleCancel() {
        this.visible = false;
      },

      //下载文件
      downloadKmDoc(record) {
        this.$notification.success({
          message: '文件开始下载...',
          duration: 1,
        });
        downloadFileName(this.url.downloadKmDoc, {docId: record.id})
      },
      //加收藏夹
      addFavouriteKmDoc(record) {
        let httpurl = '';
        let method = '';
        httpurl += this.url.addFavouriteKmDoc;
        method = 'post';
        console.info("-------id-------" + JSON.stringify(record.id))
        httpPostAction(httpurl, {docId: record.id}, method).then((res) => {
          if (res.success) {
            this.$message.success("收藏成功!");
            // this.loadData();
            record.favourite = 1;
          } else {
            this.$message.warning("收藏失败!");
          }
        }).finally(() => {
        })
      },

      ranking(index) {
        // 根据索引返回一个对象
        return {
          'active': index === 0, // 第一名
          'active2': index === 1, // 第二名
          'active3': index === 2, // 第三名
          // 可以继续添加更多的类名和条件判断
        };
      },

      getClasses(index) {
        // 根据索引返回一个对象
        return {
          'Ranking1': index === 0, // 第一名
          'Ranking2': index === 1, // 第二名
          'Ranking3': index === 2, // 第三名
          // 'hover-effect': index >= 0,
          // 可以继续添加更多的类名和条件判断
        };
      },

      //取消收藏夹
      delFavouriteKmDoc(record) {
        let httpurl = '';
        let method = '';
        httpurl += this.url.delFavouriteKmDoc;
        method = 'delete';
        httpPostAction(httpurl, {docId: record.id}, method).then((res) => {
          if (res.success) {
            this.$message.success("取消收藏成功!");
            // this.loadData();
            record.favourite = 0;
          } else {
            this.$message.warning("取消收藏失败!");
          }
        }).finally(() => {
        })
      },



    }
  }
</script>

<style>
  @import "~@assets/less/common.less";
  .checkbox .ant-checkbox-wrapper {
    color: #2e2b2b !important;
  }

  hr{
    border-color: #f2f2f2
  }


  .pagination-container .el-pagination {
    display: flex;
    justify-content: flex-end;
    /*text-align: right; !* 将分页组件靠右显示 *!*/
    /*margin-top: 10px; !* 根据需要添加上边距 *!*/
  }

  /* 确保分页组件的总记录数部分靠左显示 */
  .el-pagination__total {
    flex: 1;
    text-align: left;
  }

  .context-list-item {
    border-bottom: 1px dashed #f4f4f4;
    margin: 15px;
    font-size: 14px;
    padding-bottom: 5px;
    cursor: pointer;
    color: #303133;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }

  /*.position-bottom-left {*/
    /*position: absolute; !* 绝对定位 *!*/
    /*bottom: 15px;       !* 距离底部15px *!*/
    /*left: 15px;         !* 距离左侧15px *!*/
  /*}*/
  @media (min-width: 1200px) {
    .position-bottom-left {
      width: 20%;
      float: left;
      margin-right: 1.5%;
    }
  }

  @media (min-width: 1200px) {
    .km-context-right {
      width: 78.5%;
      float: right;
    }
  }
  @media (min-width: 1200px) {
  .km-page {
    width: 80%;
    margin: auto;
  }
  }

  @media (min-width: 1200px) {
    .kmb-context-view {
      width: 100%;
      height: 20px;
    }
  }
</style>

<style lang="less" scoped>
  /* 排行榜样式如下：*/
  .rank {
    margin-left: 20px;

    .list {
      padding: 0;
      list-style: none;

      li {
        margin-top: 10px;
        white-space: nowrap; /* 保持文本在一行显示 */
        overflow: hidden; /* 隐藏溢出的内容 */
        text-overflow: ellipsis; /* 添加省略号 */

        span {
          /*color: #606266;*/
          font-size: 14px;
          line-height: 22px;

          &:first-child {
            background-color: #f5f5f5;
            border-radius: 20px;
            display: inline-block;
            font-size: 12px;
            font-weight: 600;
            margin-right: 24px;
            height: 20px;
            line-height: 20px;
            width: 30px;
            text-align: center;
          }
          &.active {
            width: 30px;
            /*margin: auto;*/
            background: url(~@/assets/bg-rank-index.png) no-repeat 50%;
            font-size: 14px;
            color: #fff;
            background-size: cover;
            line-height: 30px;
            height: 34px;
          }
          &.active2 {
            width: 30px;
            /*margin: auto;*/
            background: url(~@/assets/yinse.png) no-repeat 50%;
            font-size: 14px;
            color: #fff;
            background-size: cover;
            line-height: 30px;
            height: 34px;
          }
          &.active3 {
            width: 30px;
            /*margin: auto;*/
            background: url(~@/assets/tongse.png) no-repeat 50%;
            font-size: 14px;
            color: #fff;
            background-size: cover;
            line-height: 30px;
            height: 34px;
          }
          &.Ranking1 {
            color: #ff0006;
            font-size: 20px;
            font-weight: bold;
          } &.Ranking2 {
              color: #e6af00;
              font-size: 18px;
              font-weight: bold;
            } &.Ranking3 {
                color: #e6af00;
                font-size: 16px;
                font-weight: bold;
              }
          &:last-child {
            float: right;
          }
        }
      }
    }
  }
  .mobile .rank {
    padding: 0 32px 32px 32px;
  }

  .hover-effect {
    cursor: pointer; /* 设置鼠标悬停时的光标为手指形状 */
    transition: color 0.3s; /* 字体颜色变化的过渡效果 */
  }

  .hover-effect:hover {
    color: #00acff; /* 鼠标悬停时的字体颜色 */
  }
</style>

